package com.foreverwin.mes.integration.handler;

import com.foreverwin.mes.core.utils.XmlFormatter;
import org.apache.cxf.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Set;

/**
 * @author Ervin Chen
 * @date 2020/1/13 9:49
 */
public class MessageLogHandler implements SOAPHandler<SOAPMessageContext> {

    Logger logger = LoggerFactory.getLogger(MessageLogHandler.class);

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        boolean out = (Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
        try {
            //进入的消息，则检查HEADER
            String address = (String) context.get(Message.REQUEST_URL);
            String message = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            context.getMessage().writeTo(outputStream);
            message = outputStream.toString();
            if (!out) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(MessageFormat.format("\nAddress: {0}", address));
                stringBuffer.append(MessageFormat.format("\nInput Message: \n{0}", XmlFormatter.format(message)));
                logger.info(stringBuffer.toString());
            } else {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(MessageFormat.format("\nAddress: {0}", address));
                stringBuffer.append(MessageFormat.format("\nOutput Message: \n{0}", XmlFormatter.format(message)));
                String str = stringBuffer.toString();
                logger.info(str);
            }
        } catch (SOAPException | IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    @Override
    public void close(MessageContext context) {

    }
}
